package main

import (
	pb "ihos/ihos"
)

type bodyinfo struct {
	id       int32   //PK
	sg       int32   //身高，cm
	xyg, xyd int32   //血压高，低，mmHg
	tz       float32 //体重
	xt       float32 //血糖
	gms      string  //过敏史
	jws      string  //既往史
	yys      string  //用药史
}

func (w *bodyinfo) GetFromDB(id int32) error {
	sql := "SELECT id,sg,xyg,xyd,tz,xt,gms,jws,yys FROM body_info WHERE id=$1"
	return DBConn.db.QueryRow(sql, id).Scan(&w.id, &w.sg, &w.xyg, &w.xyd, &w.tz, &w.xt, &w.gms, &w.jws, &w.yys)
}

func (w *bodyinfo) SaveToDB(id int32) error {
	sql := ""
	var err error
	if id > 0 { //update
		sql = "UPDATE body_info set sg=$1,xyg=$2,xyd=$3,tz=$4,xt=$5,gms=$6,jws=$7,yys=$8 where id=$9 RETURNING id"
		err = DBConn.db.QueryRow(sql, w.sg, w.xyg, w.xyd, w.tz, w.xt, w.gms, w.jws, w.yys, w.id).Scan(&w.id)
	} else { //insert
		sql = "INSERT INTO body_info(sg,xyg,xyd,tz,xt,gms,jws,yys) VALUES($1,$2,$3,$4,$5,$6,$7,$8) RETURNING id"
		err = DBConn.db.QueryRow(sql, w.sg, w.xyg, w.xyd, w.tz, w.xt, w.gms, w.jws, w.yys).Scan(&w.id)
	}
	return err
}

func (w *bodyinfo) fromPB(p *pb.BodyInfoL1) {
	w.id = p.GetID()
	w.sg = p.GetSG()
	w.xyg = p.GetXYG()
	w.xyd = p.GetXYD()
	w.tz = p.GetTZ()
	w.xt = p.GetXT()
	w.gms = p.GetGMS()
	w.jws = p.GetJWS()
	w.yys = p.GetYYS()
}

func (w *bodyinfo) toPB() *pb.BodyInfoL1 {
	p := &pb.BodyInfoL1{
		ID:  w.id,
		SG:  w.sg,
		TZ:  w.tz,
		GMS: w.gms,
		JWS: w.jws,
		XYG: w.xyg,
		XYD: w.xyd,
		XT:  w.xt,
		YYS: w.yys,
	}
	return p
}
